;(function (win, doc) {
  let inquireTpl = document.getElementById('inquireCon').innerHTML,
      brandTpl = document.getElementById('brandCon').innerHTML,
      classifyTpl = document.getElementById('classifyCon').innerHTML,
      inquireCon = mui('#item1 .goodstyle')[0],
      brandCon = mui("#item2 .goodslist")[0],
      classifyCon = mui('#item3 .goodslist')[0],
      goodstyleCon = mui('.bgwhite .goodstyle')[0],
      searchInp = mui('.searchinput input')[0],
      ensureBtn = mui('.sure')[0],
      resetBtn = mui('.reset')[0],
      Url = window.location.search,
      SearchKey = decodeURIComponent(Url.split("=")[1]),//转义
      ajaxUrl = 'http://61.147.125.185:8080',
      searchUrl = ajaxUrl + '/pawnShop/m/getMGoodsHome',
      brandUrl = ajaxUrl + '/pawnShop/b/getBrand',
      classifyUrl = ajaxUrl + '/pawnShop/b/getBrandType',
      brandId = [],
      classifyId = [],
      pageIndex = 1,
      screen = '';
  mui.init({
    pullRefresh: {
      container: '#item1',
      height: '50px',
      range: '100px',
      down: {
        style: 'circle',
        auto: false,
        callback: function() {
          globalSearch({pageIndex: 1,
            pageSize: 10})
          mui('#item1').pullRefresh().endPulldownToRefresh()
          
        }
      },
      up: {
        height: ".5rem",
        contentrefresh: '正在加载...',
        contentnomore: '没有更多数据了',
        callback: function() {
          let startSalePrice = mui('#item4 .areabox .startSalePrice')[0].value,
          endSalePrice = mui('#item4 .areabox .endSalePrice')[0].value, //  获取最高价格
          human = mui('#item4 .human .active')[0].innerHTML, // 获取款式
          state = mui('#item4 .percentage .active')[0].innerHTML // 成色
          globalSearch({
            pageIndex: pageIndex,
            pageSize: 10,
            title: '包',
            brand_code: brandId.join(','),
            type_code: classifyId.join(','),
            startSalePrice: startSalePrice,
            endSalePrice: endSalePrice,
            human: human,
            state: state,
            upwardPull: 'pull'
          })
          pageIndex += 1
        }
      }
    }
  })    
  function init() { // 定义初始话方法
    searchInp.value = SearchKey == 'undefined' ? '' : SearchKey
    globalSearch({
      pageIndex: 1,
      pageSize: 10,
      title: searchInp.value
    })
    condition(brandUrl, brandTpl, brandCon, 1, brandId)
    condition(classifyUrl, classifyTpl, classifyCon, 2, classifyId)
    brandClickHander(brandCon, brandId)
    brandClickHander(classifyCon, classifyId)
    tagsAct()
    judgeTab()
  }
  // // 判断当前在哪一个tab页
  function judgeTab () {
    mui(".secondtab").on('tap', 'a', function (){
      switch ($(this).index()) {
        case 0:
          plus.webview.currentWebview().setPullToRefresh({support:true,style:"circle"})
          let slide = mui('.slidescreen')[0]
          if (slide.classList.contains('active')) {
            slide.classList.remove('active')
          } else {
            slide.classList.add('active')
          }
          break;
        case 1:
          
          console.log(1)
          break;
        case 2:
          
          console.log(2)
          break;
        case 3:
          
          console.log(3)
          break;   
      }
      if ($(this).index() !== 0) {
        plus.webview.currentWebview().setPullToRefresh({support:false})
      }
    })
  }
  // 统一搜索ajax请求方法方法
  function globalSearch () {
    let searchData = JSON.stringify(...arguments)
    console.log(searchData)
    mui.ajax(searchUrl, {
      type: 'POST',
      data: searchData,
      dataType: 'json',
      headers: {
        'Content-Type': 'application/json'
      },
      success: function (data) {
        console.log(data)
        if (data.code === '200' && data.data.content !== null) {
          let packageList = data.data.content,
              len = packageList.length,
              content = '';
          for (let i = 0; i < len; i++) {
            content += setTplToHTML(inquireTpl, regTpl, {
              id: packageList[i].id,
              imgs: packageList[i].imgs[0],
              state: packageList[i].state,
              title: packageList[i].title,
              human: packageList[i].human,
              sale_price: packageList[i].sale_price,
              price_font: packageList[i].price_font
            })
          }
          inquireCon.innerHTML = content
          // console.log(<arguments></arguments>)
          mui('#item1').pullRefresh().endPullupToRefresh(false)
          $('.without').css({'display': 'none'})
          $(inquireCon).css({'display': 'block'})
        } else {
          $('.without').css({'display': 'block'})
          $(inquireCon).css({'display': 'none'})
        }
      },
      error: function (err) {
        mui.alert("请检查您的网络")
      }
    })
  }
  // 品牌,分类ajax 请求方法
  function condition (url, Tpl, Con, type,arrId) {
    mui.ajax(url, {
      type: 'GET',
      success: function (data) {
        if (data.code === "200" && data.data.content !== null) {
          console.log(data.data)
          let conditionList = data.data,
              len = conditionList.length,
            content = '';
          for (let i = 0; i < len; i ++) {
            if (type === 1) {
              content += setTplToHTML(Tpl, regTpl, {
                brandCode: conditionList[i].brandCode,
                brand: conditionList[i].brand
              })
            } else {
              content += setTplToHTML(Tpl, regTpl, {
                typeCode: conditionList[i].typeCode,
                typeName: conditionList[i].typeName
              })
            }
          }
          Con.innerHTML = content
          $(Con).children()[0].classList.add('active')
          arrId.push($(Con).children()[0].getAttribute('data-code'))
        }
      },
      error: function (err) {
        mui.alert('请检查您的网络')
      }
    })
  }
  // 输入框搜索事件
  searchInp.addEventListener('keydown', function (event) {
    let inpVal = searchInp.value
    if (event.keyCode === 13){
      globalSearch({
        pageIndex: 1,
        pageSize: 10,
        title: inpVal,
      })
      $(searchInp).blur()
    }
  })
 
  // 智能排序
  mui('.slidescreen .info').on('tap', 'p', function(e) {
    this.classList.add('selected')
    $(this)
      .siblings()
      .removeClass('selected')
    let sort = $(this)
      .index()
      .toString()
      globalSearch({
        sort: sort
      })
    mui('.slidescreen')[0].classList.remove('active')
  })
  
  // 品牌搜索点击
  function brandClickHander (ele, arr) {
    mui(ele).on("tap", 'li', function () {
      let getCusorm = this.getAttribute('data-code')
      if (this.classList.contains('active')) {
        this.classList.remove('active')
        arr.splice(arr.indexOf(getCusorm), 1)
      } else {
        this.classList.add("active")
        arr.push(getCusorm)
      }
    })
  }
  // 点击确定按钮查找
  ensureBtn.addEventListener('tap', demandHandler)
  function demandHandler() {
    let startSalePrice = mui('#item4 .areabox .startSalePrice')[0].value,
        endSalePrice = mui('#item4 .areabox .endSalePrice')[0].value, //  获取最高价格
        human = mui('#item4 .human .active')[0].innerHTML, // 获取款式
        state = mui('#item4 .percentage .active')[0].innerHTML // 成色
    globalSearch({
      pageIndex: 1,
      pageSize: 10,
      title: '包',
      brand_code: brandId.join(','),
      type_code: classifyId.join(','),
      startSalePrice: startSalePrice,
      endSalePrice: endSalePrice,
      human: human,
      state: state
    })
    mui('#segmentedControl a')[0].classList.add('mui-active')
    $($('#segmentedControl a')[0]).siblings().removeClass('mui-active')
    $('.mui-content').removeClass('mui-active')
    goodstyleCon.parentNode.classList.add('mui-active')
  }
  // 点击重置按钮
  resetBtn.addEventListener('tap', function () {
    $(brandCon).children()[0].classList.add('active')
    $($(brandCon).children()[0]).siblings().removeClass('active')
    $(classifyCon).children()[0].classList.add('active')
    $($(classifyCon).children()[0]).siblings().removeClass('active')
    mui('#item4 .human a')[0].classList.add('active')
    mui('#item4 .percentage a')[0].classList.add('active')
    $(mui('#item4 .human a')[0]).siblings().removeClass('active')
    $(mui('#item4 .percentage a')[0]).siblings().removeClass('active')
    mui('#item4 .areabox .startSalePrice')[0].value = ''
    mui('#item4 .areabox .endSalePrice')[0].value = ''
  })
  // 刷选tab 按钮切换
  function tagsAct () {
    let tagsActAll = mui('.tagsAct'),
        len = tagsActAll.length
    for (var i = 0; i < len; i++) {
      mui(tagsActAll[i]).on('tap', 'a', function () {
        this.classList.add('active');
        $(this).siblings().removeClass('active')
      })
    }
  }
  // 正则替换模板字符串方法
  function regTpl () {
    return new RegExp(/{{(.*?)}}/, 'gim')
  }
  // 模板替换函数
  function setTplToHTML (tpl, regExp, opt) {
    return tpl.replace(regExp(), function (node, key) {
      return opt[key]
    })
  }
  init()
})(window, document)